
var User = require('../models/user')

exports.showSignin = function (req, res) {
	res.render('signin', { 
		title: '登陆页'
	})
}

exports.showSignup = function (req, res) {
	res.render('signup', { 
		title: '注册页'
	})
}



exports.list = function (req, res) {
	User.fetch(function (err, users) {
		if(err){
			console.log(err)
		}

		res.render('userlist', { 
			title: 'imooc user 列表页',
			users: users
		})

	})
}

// signup
exports.signup = function (req, res) {
	var _user = req.body.user

	User.findOne({name: _user.name}, function (err, user) {
		if(err) {
			return res.redirect('/signup')
		}

		if(user) {
			return res.redirect('/signup')
		}
		
		var user = new User(_user)

		user.save(function (err, user) {
			if(err){
				return res.redirect('/signup')
			}
			return res.redirect('/')
		})
	})
}

// signin
exports.signin = function (req, res) {
	var _user = req.body.user
	var name = _user.name
	var password = _user.password

	User.findOne({name: name}, function (err, user) {
		if(err){
			console.log(err)
			return res.redirect('/signin')
		}

		if(!user){
			return res.redirect('/signin')
		}

		user.comparePassword(password, function (err, isMatch) {
			if(err){
				console.log(err)
			}

			if(isMatch){
				req.session.user = user
				return res.redirect('/')
			}
			else {
				res.redirect('/signin')
			}
		})
	})
}

// logout
exports.logout = function (req, res) {
	delete req.session.user
	return res.redirect('signin')
}

// signin required
exports.signinRequired = function (req, res, next) {
	var user = req.session.user
	console.log("user:" + user)
	if(!user) {
		return res.redirect('/signin')
	}
	next()
}

// signin required
exports.adminRequired = function (req, res, next) {
	var user = req.session.user

	console.log("user.role:" + user.role)
	if(user.role < 50) {
		return res.redirect('/signin')
	}
	console.log("user go:" + user)
	
	next()
}